package data

import (
	"blog/model"
	"crypto/md5"
	"encoding/hex"
	"errors"

	"gitee.com/xchengli/blog-lib/database"
	"gitee.com/xchengli/blog-lib/zlog"

	"github.com/gin-gonic/gin"
)

type AdminUserDataService struct{}

// CheckLogin 检查管理员登录
func (s *AdminUserDataService) CheckLogin(ctx *gin.Context, userName, userPass string) (*model.AdminUser, error) {
	if userName == "" || userPass == "" {
		return nil, model.ERR_NO_LOGIN
	}

	db := database.GetDB()
	var adminUser model.AdminUser

	// 对密码进行MD5加密
	hasher := md5.New()
	hasher.Write([]byte(userPass))
	encryptedPass := hex.EncodeToString(hasher.Sum(nil))

	err := db.Where("name = ? AND pass = ?", userName, encryptedPass).First(&adminUser).Error
	if err != nil {
		zlog.Error(ctx, err)
		return nil, model.ERR_NO_LOGIN
	}

	return &adminUser, nil
}

// GetAdminUserByID 根据ID获取管理员用户
func (s *AdminUserDataService) GetAdminUserByID(ctx *gin.Context, id int64) (*model.AdminUser, error) {
	db := database.GetDB()
	var adminUser model.AdminUser

	err := db.Where("id = ?", id).First(&adminUser).Error
	if err != nil {
		zlog.Error(ctx, err)
		return nil, err
	}

	return &adminUser, nil
}

// CreateAdminUser 创建管理员用户
func (s *AdminUserDataService) CreateAdminUser(ctx *gin.Context, adminUser *model.AdminUser) error {
	if adminUser.Name == "" || adminUser.Pass == "" {
		return errors.New("用户名和密码不能为空")
	}

	db := database.GetDB()

	// 对密码进行MD5加密
	hasher := md5.New()
	hasher.Write([]byte(adminUser.Pass))
	adminUser.Pass = hex.EncodeToString(hasher.Sum(nil))

	return db.Create(adminUser).Error
}

// UpdateAdminUser 更新管理员用户
func (s *AdminUserDataService) UpdateAdminUser(ctx *gin.Context, adminUser *model.AdminUser) error {
	db := database.GetDB()

	// 如果密码不为空，则进行MD5加密
	if adminUser.Pass != "" {
		hasher := md5.New()
		hasher.Write([]byte(adminUser.Pass))
		adminUser.Pass = hex.EncodeToString(hasher.Sum(nil))
	}

	return db.Save(adminUser).Error
}

// DeleteAdminUser 删除管理员用户
func (s *AdminUserDataService) DeleteAdminUser(ctx *gin.Context, id int64) error {
	db := database.GetDB()
	return db.Delete(&model.AdminUser{}, id).Error
}

// GetAllAdminUsers 获取所有管理员用户
func (s *AdminUserDataService) GetAllAdminUsers(ctx *gin.Context) ([]model.AdminUser, error) {
	db := database.GetDB()
	var adminUsers []model.AdminUser

	err := db.Find(&adminUsers).Error
	if err != nil {
		zlog.Error(ctx, err)
		return nil, err
	}

	return adminUsers, nil
}
